package com.gis.halodepok;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.util.ByteArrayBuffer;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;

public class AlarmReciever extends BroadcastReceiver {
	Context context;

	@Override
	public void onReceive(Context context, Intent intent) {
		this.context = context;
		new AsyncTaskRunner().execute("");
	}

	class AsyncTaskRunner extends AsyncTask<String, String, String> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		public void DownloadFromUrl() {

			try {
				File root = context.getDir("haha", Context.MODE_PRIVATE);

				File dir = new File(root.getAbsolutePath() + "/xmls");
				if (dir.exists() == false) {
					dir.mkdirs();
				}
				for (int i = 0; i < 27; i++) {
					URL url = new URL("http://hallodepok.herokuapp.com/" + i
							+ ".xml"); // you can write here any link
					File file = new File(dir, i + ".xml");
					if (file.exists() == false) {
						file.createNewFile();
					}
					long startTime = System.currentTimeMillis();
					Log.d("DownloadManager", "download begining");
					Log.d("DownloadManager", "download url:" + url);
					Log.d("DownloadManager", "downloaded file name:" + i
							+ ".xml");

					/* Open a connection to that URL. */
					URLConnection ucon = url.openConnection();

					/*
					 * Define InputStreams to read from the URLConnection.
					 */
					InputStream is = ucon.getInputStream();
					BufferedInputStream bis = new BufferedInputStream(is);

					/*
					 * Read bytes to the Buffer until there is nothing more to
					 * read(-1).
					 */
					ByteArrayBuffer baf = new ByteArrayBuffer(5000);
					int current = 0;
					while ((current = bis.read()) != -1) {
						baf.append((byte) current);
					}

					/* Convert the Bytes read to a String. */
					FileOutputStream fos = new FileOutputStream(file);
					fos.write(baf.toByteArray());
					fos.flush();
					fos.close();
					Log.d("DownloadManager",
							"download ready in"
									+ ((System.currentTimeMillis() - startTime) / 1000)
									+ " sec");
				}

			} catch (IOException e) {
				Log.d("DownloadManager", "Error: " + e);
			}

		}

		public Document getDomElement(String xml) {
			Document doc = null;
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			try {

				DocumentBuilder db = dbf.newDocumentBuilder();

				InputSource is = new InputSource();
				is.setCharacterStream(new StringReader(xml));
				doc = db.parse(is);

			} catch (ParserConfigurationException e) {
				Log.e("Error: ", e.getMessage());
				return null;
			} catch (SAXException e) {
				Log.e("Error: ", e.getMessage());
				return null;
			} catch (IOException e) {
				Log.e("Error: ", e.getMessage());
				return null;
			}
			// return DOM
			return doc;
		}

		// XML node keys

		private String resp;

		@Override
		protected String doInBackground(String... params) {
			DownloadFromUrl();
			return resp;
		}

	}
}
